package com.vates.curso.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.vates.curso.dao.UserDao;
import com.vates.curso.entities.Role;
import com.vates.curso.entities.User;
import com.vates.curso.service.SecurityService;

@Component("securityService")
public class SecurityServiceImpl implements SecurityService {

	@Autowired
	private UserDao userDao;

	@Autowired
	@Qualifier("authenticationManager")
	private AuthenticationManager authenticationManager;

	@Transactional
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		if (username != null && !username.equals("")) {
			User user = userDao.getUserByName(username);
			if (user == null) {
				return null;
			}
			Iterator<Role> it = user.getUserRoles().iterator();
			List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
			while (it.hasNext()) {
				String authority = it.next().getAuthority();
				GrantedAuthority grantedAuth = new UserGrantedAuthority(
						authority);
				grantedAuthorities.add(grantedAuth);
			}

			CustomUserDetails cu = new CustomUserDetails(user.getUserId(),
					user.getUserName(), user.getPassword(),
					grantedAuthorities.toArray(new GrantedAuthority[] {}),
					user.getEnabled());
			return cu;
		} else {
			return null;
		}

	}

	public boolean login(String userName, String password) {
		try {
			Authentication authenticate = authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(
							userName, password));
			if (authenticate.isAuthenticated()) {
				SecurityContextHolder.getContext().setAuthentication(
						authenticate);
				return true;
			}
		} catch (AuthenticationException e) {
		}
		return false;
	}

}
